<template>
  <div>
    <!-- 整车保修期维护--车厂 -->
    <TopFilter ref="TopFilterss111" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="90" @filterChange="changeHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :fetchapi="fetchapi"
      :datakey="'records'"
      :onColumnsChange="columns => (this.columns = columns)"
      :is-select-column="true"
      :onRowSelectChange="selectChange"

    >
      <template slot="controls" slot-scope="props">
                <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">新增</multiuse-button>
        <multiuse-button size="small" type="primary" icon="el-icon-check" :click="qiyong.bind()" :disabled="disableds">启用</multiuse-button>
        <multiuse-button size="small" type="primary" icon="el-icon-close" :click="tingyong.bind()" :disabled="disableds">禁用</multiuse-button>
        <multiuse-button size="small" type="primary"  :loading="exportLoading" :click="exportFileBtn.bind()">下载</multiuse-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="visibleAdd" :title="'整车保修期新增'" destroyOnClose width="850px" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <AddForm @close="closeAdd" @save="saveAdd"></AddForm>
    </BaseDialog>
    <BaseDialog :visible.sync="emitVisible" title="整车保修期编辑" width="850px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <editForm @close="emitCloseHandle" @save="emitChange" :rowData="rowData" />
    </BaseDialog>
    <BaseDialog :visible.sync="showImport" icon="el-icon-upload" :closable="false" title="导入" width="800px" destroyOnClose :containerStyle="{ height: 'calc(100% - 120px)', overflow: 'auto', paddingBottom: '60px' }">
      <importExcel @close="showImport = false" @importclose="editsave1()" url="/api/cms_claimfac/rPVhlPeriod/importExcel"/>
    </BaseDialog>
  </div>
</template>
<script>
import AddForm from './AddForm.vue';
import editForm from './editForm.vue';
import { exportExcelFile } from '@/utils/index';
import {  getModelsdictt } from '@/api/dictionary/index';
import importExcel from '@/pages/claimDemage/tools/importExcel.vue';
import { getListByPage,  piliangqiyong, piliangtingyong,getListForExport, downloadModel } from '@/api/claim/factory/FullCarWarrantyMaintain';
import {dictionary} from'@/utils/dictMixin';
export default {
    mixins: [dictionary],
  components: {
    AddForm,
    importExcel,
    editForm
  },
  data() {
    return {
      disableds: true,
      visible: false,
      rowData: {},
      collapse: true,
      emitVisible: false,
      showImport: false,
      exportLoading: false,
      fetchapi: getListByPage,
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中的行
      visibleAdd: false,
      modelNameList: []
    };
  },
  created() {
    this.chuqi();
  },
  methods: {
    async chuqi(){
      const res = await getModelsdictt();
      if (res.resultCode == 200) {
        res.data.forEach(x => {
              if(x != null){
                this.modelNameList.push({text: x.MODEL_NAME,value: x.MODEL_CODE, id: x.MODEL_ID});
              }
            });
        this.topFilterInit.find(x => x.fieldName == 'modelCode').itemList = this.modelNameList;
      }
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      this.disableds = this.selectedRows.length <= 0;
    },
    close() {
      this.visible = false;
    },
    chooseOrderNo() {
      this.visible = true;
    },
    //批量启用
    async qiyong() {
      if (this.selectedRows.length > 0) {
        let str = '';
        this.selectedRows.map(x => {
          str += x.vpId + ',';
        });
        console.log(str);
        const res = await piliangqiyong({ ids: str, status: '1' });
        this.fetchParams = { ...this.fetchParams };
      } else {
        return this.$notify.warning({title: '提示信息', message: '请勾选后再进行启用！'});
      }
    },
    //批量停用
    async tingyong() {
      if (this.selectedRows.length > 0) {
        let str = '';
        this.selectedRows.map(x => {
          str += x.vpId + ',';
        });
        console.log(str);
        const res = await piliangtingyong({ids: str, status: '0'});
        this.fetchParams = {...this.fetchParams};
      } else {
        return this.$notify.warning({title: '提示信息', message: '请勾选后再进行停用！'});
      }
    },
    save(obj) {
      this.topFilterInit.find(x => x.fieldName == 'modelCode').initialValue = obj[0].modelCode;
      this.visible = false;
    },
    add() {
      this.visibleAdd = true;
    },
    emitFun(val) {
      this.rowData = val;
      this.emitVisible = true;
    },
    emitCloseHandle() {
      this.emitVisible = false;
    },
    emitChange() {
      this.emitVisible = false;
      this.fetchParams = { ...this.fetchParams };
    },
    closeAdd() {
      this.visibleAdd = false;
    },
    saveAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    // Excel更新导入
    showImportFun() {
      this.showImport = true;
    },
    //下载模板
    downloadTemplate() {
      this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true;
        downloadModel().then(res => {
          console.log(res);
          exportExcelFile(res.data, '整车保修期维护导入模板');
          this.exportLoading = false;
        });
      });
    },
    // 导出
    async exportFileBtn() {
      this.loading1 = true;
      getListForExport(this.fetchParams).then((res) => {
        exportExcelFile(res.data, '整车保修期');
        this.loading1 =false;
      });
    },
    editsave1() {
      this.showImport = false;
      this.fetchParams = { ...this.fetchParams };
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = Object.assign({}, this.fetchParams, val);
      console.log(val);
    },
    //搜索数据
    topFilterInitFun() {
      return [
        {
          type: 'SELECT',
          label: '适用车型',
          fieldName: 'modelCode',
          placeholder: '请选择适用车型...',
          initialValue: '',
          filterable: true,
          itemList: []
        },
        {
          type: 'SELECT',
          label: '营运类型',
          fieldName: 'vpType',
          placeholder: '请选择营运类型...',
          initialValue: '',
          filterable: true,
          itemList: [
            { text: '运营', value: '55841001' },
            { text: '非运营', value: '55841002' }
          ]
        },
        {
          type: 'INPUT',
          label: '保修期',
          fieldName: 'vpPeriod',
          initialValue: '',
          placeholder: '请输入保修期...',
          rules: [
            {
              validator: (rule, value, callback) => {
                if(value) {
                  if (Number.isInteger(Number(value))) {
                    callback();
                  } else {
                    callback(new Error('请输入数字值'));
                  }
                } else {
                  callback();
                }
              },
              trigger: ['blur', 'change'],
            },
          ],
          unitRender: () => {
            return <span>(月)</span>;
          },
        },
        {
          type: 'INPUT',
          label: '保修里程',
          fieldName: 'vpMile',
          initialValue: '',
          placeholder: '请输入保修里程...',
          rules: [
            {
              validator: (rule, value, callback) => {
                if(value) {
                  if (Number.isInteger(Number(value))) {
                    callback();
                  } else {
                    callback(new Error('请输入数字值'));
                  }
                } else {
                  callback();
                }
              },
              trigger: ['blur', 'change'],
            },
          ],
          unitRender: () => {
            return <span>(KM)</span>;
          },
        },
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          render: (props, h) => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.emitFun(props.row)}>
                  编辑
                </multiuse-button>
              </div>
            );
          }
        },
        {title: '状态', dataIndex: 'statusStr', sorter: true},
        {title: '适用车型', dataIndex: 'modelName', sorter: true},
        {title: '营运类型', dataIndex: 'typeName', sorter: true},
        {title: '保修期（月）', dataIndex: 'vpPeriod', sorter: true},
        {title: '保修里程（KM）', dataIndex: 'vpMile', sorter: true},
        {title: '创建人', dataIndex: 'createdBy', sorter: true},
        {title: '创建时间', dataIndex: 'createdAt', sorter: true},
        {title: '修改人', dataIndex: 'updatedBy', sorter: true},
        {title: '修改时间', dataIndex: 'updatedAt', sorter: true}
      ];
    },

  }
};
</script>

<style lang="less" scoped></style>
